'''

with 和上下文管理器

'''

def read(file):
    f = open(file, 'w')
    try:
        f.write("xxxx")
    except Exception as e:
        print(e)
    finally:
        f.close()


def read_(file):
    with open(file, 'w') as f:
        f.write('xxxx')


# 上下文管理器

# 1. 对象要实现 __enter__  和 __exit__ 方法，

class File():
    def __init__(self, file, mode):
        self.file = file
        self.mode = mode
    def __enter__(self):
        self.file = open(self.file, self.mode)
        return self.file
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_tb, exc_val,exc_type)
        self.file.close()


with File('C:\\Users\\DUSHA001\\Desktop\\servers.txt', 'r') as f:
    print(f.read())
    print(f.read())

# 2. 还可以用contextlib
from contextlib import contextmanager
@contextmanager
def my_open(path, mode):
    f = open(path, mode)
    yield f
    f.close()

with my_open('C:\\Users\\DUSHA001\\Desktop\\servers.txt', 'r') as f:
    print(f.readline())
    print(f.readline())
    print(f.readline())